<template>
  <div class="favorites-page">
    <!-- 空状态 -->
    <van-empty
      v-if="!loading && favoriteArticles.length === 0"
      image="search"
      description="暂无收藏文章"
    >
      <van-button
        round
        type="primary"
        class="bottom-button"
        @click="goToHome"
      >
        去首页看看
      </van-button>
    </van-empty>

    <!-- 收藏列表 -->
    <div v-else-if="favoriteArticles.length > 0" class="favorites-list">
      <!-- 操作栏 -->
      <div class="action-bar">
        <div class="count-info">
          共 {{ favoriteArticles.length }} 篇收藏
        </div>
        <van-button
          v-if="!isEditMode"
          type="danger"
          size="small"
          plain
          @click="enterEditMode"
        >
          管理
        </van-button>
        <div v-else class="edit-actions">
          <van-button
            size="small"
            @click="exitEditMode"
          >
            取消
          </van-button>
          <van-button
            type="danger"
            size="small"
            @click="deleteSelected"
            :disabled="selectedItems.length === 0"
          >
            删除({{ selectedItems.length }})
          </van-button>
        </div>
      </div>

      <!-- 全选选项 -->
      <div v-if="isEditMode" class="select-all">
        <van-checkbox
          v-model="selectAll"
        >
          全选
        </van-checkbox>
      </div>

      <!-- 文章列表 -->
      <van-checkbox-group v-if="isEditMode" v-model="selectedItems" class="article-list">
        <div
          v-for="article in favoriteArticles"
          :key="article.news_id || article.newsId"
          class="article-item"
          @click="handleItemClick(article)"
        >
          <!-- 编辑模式下的选择框 -->
          <van-checkbox
            :name="article.news_id || article.newsId"
            class="item-checkbox"
            @click.stop
          />

          <div class="article-content">
            <h3 class="article-title">{{ article.title }}</h3>
            <p class="article-summary">
              {{ article.contentPreview || (article.content_text ? article.content_text.substring(0, 100) + '...' : '无内容摘要') }}
            </p>
            <div class="article-meta">
              <span class="category">{{ article.category }}</span>
              <span class="time">{{ formatTime(article.pub_time || article.pubTime) }}</span>
              <span v-if="article.section" class="section">{{ article.section }}</span>
            </div>
          </div>
        </div>
      </van-checkbox-group>

      <!-- 非编辑模式的文章列表 -->
      <div v-else class="article-list">
        <div
          v-for="article in favoriteArticles"
          :key="article.news_id || article.newsId"
          class="article-item"
          @click="handleItemClick(article)"
        >
          <div class="article-content">
            <h3 class="article-title">{{ article.title }}</h3>
            <p class="article-summary">
              {{ article.contentPreview || (article.content_text ? article.content_text.substring(0, 100) + '...' : '无内容摘要') }}
            </p>
            <div class="article-meta">
              <span class="category">{{ article.category }}</span>
              <span class="time">{{ formatTime(article.pub_time || article.pubTime) }}</span>
              <span v-if="article.section" class="section">{{ article.section }}</span>
            </div>
          </div>

          <!-- 右侧箭头 -->
          <van-icon
            name="arrow"
            class="arrow-icon"
          />
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <van-loading
      v-if="loading"
      type="spinner"
      color="#1989fa"
      class="loading-center"
    >
      加载中...
    </van-loading>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'
import { showConfirmDialog, showToast, showSuccessToast } from 'vant'
import { articleApi } from '../utils/api'
import { useFavoritesStore } from '../stores/favorites'
import { formatTime } from '../utils/dateUtils'

const router = useRouter()
const favoritesStore = useFavoritesStore()

// 响应式数据
const { favoriteArticles, loading } = storeToRefs(favoritesStore)
const isEditMode = ref(false)
const selectedItems = ref([])

// 调试信息
const debugInfo = ref({
  show: false,
  favoriteIdsCount: 0,
  favoriteIds: [],
  successCount: 0,
  failedIds: []
})

// 计算属性
const selectAll = computed({
  get() {
    return favoriteArticles.value.length > 0 && selectedItems.value.length === favoriteArticles.value.length
  },
  set(value) {
    if (value) {
      selectedItems.value = favoriteArticles.value.map(item => item.news_id || item.newsId)
    } else {
      selectedItems.value = []
    }
  }
})

// 时间格式化函数已移至 @/utils/dateUtils.js

// 加载收藏文章
const loadFavorites = async () => {
  try {
    // 使用Pinia store加载收藏文章
    const result = await favoritesStore.loadFavoriteArticles(articleApi)

    // 更新调试信息
    debugInfo.value.favoriteIdsCount = favoritesStore.favoriteIds.length
    debugInfo.value.favoriteIds = [...favoritesStore.favoriteIds]
    debugInfo.value.successCount = result.articles ? result.articles.length : 0
    debugInfo.value.failedIds = []

    if (result.success) {
      console.log(`成功加载 ${result.articles.length} 篇收藏文章`)

      // 显示加载结果的详细信息
      const messages = []
      if (result.articles.length > 0) {
        messages.push(`成功加载 ${result.articles.length} 篇文章`)
      }
      if (result.removedCount > 0) {
        messages.push(`移除 ${result.removedCount} 篇失效文章`)
      }
      if (result.temporaryFailedCount > 0) {
        messages.push(`${result.temporaryFailedCount} 篇文章暂时无法加载`)
      }

      if (messages.length > 1) {
        showToast(messages.join('，'))
      } else if (result.removedCount > 0) {
        showToast(`已移除 ${result.removedCount} 篇失效文章`)
      }
    } else {
      console.error('加载收藏失败:', result.error)
      showToast('加载收藏失败，请稍后重试')
    }

  } catch (error) {
    console.error('加载收藏失败:', error)
    showToast('加载收藏失败')
  }
}

// 进入编辑模式
const enterEditMode = () => {
  isEditMode.value = true
  selectedItems.value = [] // 确保进入编辑模式时没有文章被选中
}

// 退出编辑模式
const exitEditMode = () => {
  isEditMode.value = false
  selectedItems.value = []
}



// 删除选中的文章
const deleteSelected = async () => {
  if (selectedItems.value.length === 0) return

  // 调试信息：检查选中的文章ID
  console.log('准备删除的文章ID:', selectedItems.value)
  console.log('当前收藏的文章ID:', favoritesStore.favoriteIds)
  console.log('当前文章列表:', favoriteArticles.value.map(a => ({
    id: a.news_id || a.newsId,
    title: a.title
  })))

  try {
    await showConfirmDialog({
      title: '确认删除',
      message: `确定要删除选中的 ${selectedItems.value.length} 篇文章吗？`,
      confirmButtonText: '删除',
      confirmButtonColor: '#ee0a24'
    })

    // 确保传递的是字符串或数字类型的ID
    const idsToDelete = selectedItems.value.map(id => {
      // 如果是字符串数字，转换为数字；如果已经是数字，保持不变
      const numId = Number(id)
      return isNaN(numId) ? id : numId
    })

    console.log('转换后的删除ID:', idsToDelete)

    // 使用Pinia store删除选中的文章
    const removedCount = favoritesStore.removeFavorites(idsToDelete)

    console.log('实际删除数量:', removedCount)

    if (removedCount > 0) {
      showSuccessToast(`已删除 ${removedCount} 篇文章`)
    } else {
      showToast('删除失败，请重试')
    }

    exitEditMode()

  } catch (error) {
    // 用户取消删除
    console.log('用户取消删除操作')
  }
}

// 处理文章项点击
const handleItemClick = (article) => {
  if (isEditMode.value) return

  // 跳转到文章详情页
  router.push({ name: 'news-detail', params: { id: article.news_id || article.newsId } })
}

// 跳转到首页
const goToHome = () => {
  router.push({ name: 'home' })
}

// 页面加载时获取收藏列表
onMounted(() => {
  loadFavorites()
})
</script>

<style scoped>
.favorites-page {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 60px; /* TabBar高度 */
}

.loading-center {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.favorites-list {
  background-color: white;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #ebedf0;
  background-color: white;
}

.count-info {
  font-size: 14px;
  color: #646566;
}

.edit-actions {
  display: flex;
  gap: 8px;
}

.select-all {
  padding: 12px 16px;
  border-bottom: 1px solid #ebedf0;
  background-color: white;
}

.article-list {
  background-color: white;
}

.article-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ebedf0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.article-item:hover {
  background-color: #f7f8fa;
}

.article-item:last-child {
  border-bottom: none;
}

.item-checkbox {
  margin-right: 12px;
}

.article-content {
  flex: 1;
  min-width: 0;
}

.article-title {
  font-size: 16px;
  font-weight: 500;
  color: #323233;
  margin: 0 0 8px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.article-summary {
  font-size: 14px;
  color: #646566;
  margin: 0 0 8px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.article-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #969799;
}

.category {
  background-color: #f2f3f5;
  padding: 2px 6px;
  border-radius: 4px;
  color: #646566;
}

.section {
  background-color: #e8f4ff;
  padding: 2px 6px;
  border-radius: 4px;
  color: #1989fa;
}

.arrow-icon {
  color: #c8c9cc;
  margin-left: 8px;
}

.bottom-button {
  margin-top: 16px;
}

.debug-info {
  background-color: #fff3cd;
  border: 1px solid #ffeaa7;
  border-radius: 8px;
  padding: 16px;
  margin: 16px;
  font-size: 14px;
}

.debug-info h4 {
  margin: 0 0 8px 0;
  color: #856404;
}

.debug-info p {
  margin: 4px 0;
  color: #856404;
}
</style>
